<template>
  <div class="serveNo">
    <page-box class="serve-pagebox">
      <template #top>
        <alert-msg
          content="SIP号码管理是SIP话机设备注册的基础，设置SIP号码后，可以通过SIP话机的管理后台填写注册地址、SIP号码账号和密码，使话机设置注册成功。管理员和企业员工可以选择已注册的SIP话机设备，作为呼叫时绑定的通话设备使用。已注册成功的话机可以在话机输入0000发送根据提示音进行绑定工号。"
        >
          <template #icon>
            <i class="MC_iconfont MC_icon-xinxi-mian"></i>
          </template>
        </alert-msg>
      </template>
      <template #search>
        <search-form :fieldList="fieldList" :form="form" @onSearchFun="hanedleSearch"></search-form>
      </template>
      <template #btn>
        <el-button type="default" class="search-btn" @click="hanedleSearch">查询</el-button>
        <!-- <el-button type="default" class="search-btn" @click="handleImportant">导入</el-button> -->
        <el-button type="primary" class="search-btn" @click="addSIPNum">新建</el-button>
      </template>
      <template #table>
        <resize-table
          :topHeight="104"
          :headers="tableHeaders"
          :data="tableData"
          :pagingData="pagingData"
          @onPageChange="handleCurrentChange"
          @onPageSizeChange="handleSizeChange"
          @onCheckHeadersChange="checkHeadersChange"
          :showPagination="true"
          :batchs="batchs"
        >
          <template #registerStatus="{ scope }">
            <span v-if="scope.row.registerStatus === 0"><i class="fail" />未注册</span>
            <span v-else-if="scope.row.registerStatus === 1"><i class="success" />已注册</span>
          </template>
          <template #oprate="{ scope }">
            <span class="edit" @click="editSIPNo(scope.row)">编辑</span>
            <span class="edit" @click="deleteSIPNum(scope.row)">删除</span>
          </template>
        </resize-table>
      </template>
    </page-box>
    <addSIPNo ref="addSIPNo" :numType="type" @onRefresh="getSipList"></addSIPNo>
    <ImportSip ref="ImportRef" @refresh="getSipList"></ImportSip>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, nextTick, getCurrentInstance, onMounted, markRaw } from 'vue'
import pageBox from '@common/components/page-box.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import searchForm from '@/common/components/base-form/form.vue'
import resizeTable from '@/common/components/resize-table/index.vue'
import addSIPNo from './add-sip.vue'
import ImportSip from './import-sip.vue'
import alertMsg from '@common/components/alert/index.vue'
import { getSIPNo, deleteSIPNo } from '@app/call-center/apis/number-manage'
import { commonStore } from '@/common/store/modules/common'
import mcCache from '@/common/utils/mc-get-cache'
import { getFormatDateTime } from '@/common/utils/common'
import { userModule } from '@/common/store/modules/user'
import deleteIcon from '@/common/components/delete-icon/index.vue'
interface State {
  fieldList: Record<string, unknown>[]
  form: any
  tableHeaders: Record<string, unknown>[]
  tableData: Record<string, unknown>[]
  pagingData: any
  staffListArr: any
  searchHeight: string
  type: string
  openShow: boolean
}
export default defineComponent({
  name: 'SIPNo',
  components: {
    searchForm,
    resizeTable,
    addSIPNo,
    alertMsg,
    ImportSip,
    pageBox
  },
  // ----------------生命周期-----------------------
  setup() {
    const USERMODULE = userModule()
    const state: State = reactive({
      fieldList: [
        {
          name: 'SIP号',
          field: 'number',
          type: 'text'
        },
        {
          name: '绑定员工',
          field: 'agentId',
          type: 'dropdown',
          choices: []
        },
        {
          name: '状态',
          field: 'registerStatus',
          type: 'dropdown',
          choices: [
            { label: '全部', value: '' },
            { label: '未注册', value: 0 },
            { label: '已注册', value: 1 }
          ]
        }
      ],
      form: {
        accountId: '',
        number: '',
        agentId: '',
        // webRtc: null,
        registerStatus: null
      },
      tableHeaders: [
        { label: 'SIP号', prop: 'number', show: true },
        { label: '状态', prop: 'registerStatus', show: true, custom: true },
        { label: '绑定员工', prop: 'uidName', show: true },
        { label: '注册设备', prop: 'registerDevice', show: true },
        { label: '注册时间', prop: 'registerTime', show: true },
        { label: '操作', prop: 'oprate', show: true, width: 160 }
      ],
      tableData: [],
      pagingData: {
        page: 1,
        total: 0,
        limit: 10
      },
      staffListArr: [],
      searchHeight: '',
      openShow: false,
      type: 'add'
    })

    const instance: any = getCurrentInstance()

    const addSIPNum = async () => {
      await nextTick()
      state.type = 'add'
      instance?.refs.addSIPNo.openAddSIPNo()
    }

    const editSIPNo = (row: any) => {
      state.type = 'edit'
      instance?.refs.addSIPNo.openAddSIPNo(row)
    }

    // 删除
    const deleteSIPNum = (row: any) => {
      ElMessageBox.confirm('删除SIP号后不可找回，请谨慎操作。', '删除', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
        icon: markRaw(deleteIcon)
      })
        .then(() => {
          deleteSIPNo({ accountId: USERMODULE.accountId || '', list: [row.id] }).then((res: any) => {
            if (res.success) {
              ElMessage.success('删除成功')
              getSipList()
            }
          })
        })
        .catch()
    }

    // 展开收起
    const handleLines = () => {
      state.openShow = !state.openShow
    }

    const hanedleSearch = () => {
      state.pagingData.page = 1
      getSipList()
    }

    // 导入
    const handleImportant = () => {
      instance?.refs.ImportRef.openOrCloseDrawer()
    }

    // 获取表格数据
    const getSipList = async () => {
      const sendData = {
        ...state.form,
        pageSize: state.pagingData.limit,
        pageNumber: state.pagingData.page,
        accountId: USERMODULE.accountId || ''
      }
      getSIPNo(sendData).then((res) => {
        if (res && res.success) {
          const list = res.data.list || []
          list.forEach((item: any) => {
            const obj: any = commonStore().publicCache.userCacheObj
            const agentObj: any = obj[item.agentId] || {}
            item.uidName = agentObj ? agentObj.name : '--'
            item.registerTime = item.registerTime ? getFormatDateTime(item.registerTime, '') : ''
          })
          state.tableData = list
          state.pagingData.total = res.data.page.total || 0
        }
      })
    }

    const handleCurrentChange = (page: number) => {
      state.pagingData.page = page
      getSipList()
    }

    const handleSizeChange = (size: number) => {
      state.pagingData.limit = size
      getSipList()
    }

    onMounted(async () => {
      getSipList()
      const userList = await mcCache.$getCache('userCache', 'hasObj')
      state.fieldList.forEach((item: any) => {
        if (item.field === 'agentId') {
          const list = userList || []
          if (list && list.length) {
            item.choices = list.map((i: any) => ({ label: `${i.agentName} [${i.agentNumber}]`, value: i._id }))
          }
        }
      })
    })

    return {
      ...toRefs(state),
      addSIPNum,
      editSIPNo,
      handleLines,
      deleteSIPNum,
      hanedleSearch,
      handleImportant,
      handleCurrentChange,
      handleSizeChange,
      getSipList
    }
  }
})
</script>

<style lang="stylus" scoped>
.serveNo
    :deep(.serve-pagebox)
      .box
        padding 16px 24px
    .search-form
        float left
        width 72%
        height 100%
    .search-oprate
        float right
        margin-top 26px
        display: flex;
        flex-direction: row;
        justify-content: flex-end;
        align-items: flex-end;
        gap: 12px;
        height: 36px;
        flex: none;
        order: 1;
        flex-grow: 0;
        margin-bottom 12px
    .search-oprate1
        margin-bottom 20px
    .search-btn
        i
            margin-right 5px
    .edit,.delete
        color var(--mc-main-color)
        cursor pointer
    .edit
        margin-right 16px
    .el-alert
        display: flex;
        flex-direction: row;
        align-items: center;
        padding: 10px 16px;
        gap: 8px;
        width: 100%;
        height: 100%;
        background: linear-gradient(0deg, rgba(28, 97, 241, 0.1), rgba(28, 97, 241, 0.1)), #FFFFFF;
        border-radius: 4px;
        flex: none;
        order: 2;
        align-self: stretch;
        flex-grow: 0;
        font-size: 14px;
        line-height: 20px;
        letter-spacing: 0.001em;
        color: rgba(0, 0, 0, 0.88);
        :deep(.el-icon)
            color var(--mc-link-color)
  :deep(.el-transfer-panel)
    width 220px
.dialog-tip
  font-style: normal;
  font-weight: 400;
  font-size: 14px;
  line-height: 24px;
  letter-spacing: 0.001em;
  color: rgba(0, 0, 0, 0.88);
  flex: none;
  order: 0;
  flex-grow: 1;
.fail, .success{
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  margin-right: 8px;
  vertical-align: middle;

  &.fail {
    background: var(--mc-error-color);
  }

  &.success {
    background: var(--mc-success-color);
  }
}
</style>
